package com.lbw.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lbw.config.BasePage;
import com.lbw.config.minio.MinioProp;
import com.lbw.entity.Subject;
import com.lbw.entity.SubjectEntity;
import com.lbw.entity.VideoEntity;
import com.lbw.result.Result;
import com.lbw.result.ResultFactory;
import com.lbw.service.SubjectEntityService;
import com.lbw.service.SubjectService;
import com.lbw.service.VideoEntityService;
import com.lbw.vo.VideoStuVo;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;
import ws.schild.jave.MultimediaInfo;
import ws.schild.jave.MultimediaObject;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lbw
 * @since 2020-09-13
 */
@RestController
@RequestMapping("/videoEntity")
@Api(tags = "视频配置")
public class VideoEntityController {

    @Autowired
    private VideoEntityService videoEntityService;
    @Autowired
    private SubjectEntityService subjectEntityService;

    @Autowired
    private SubjectService subjectService;

    private static final String MINIO_BUCKET = "video";

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioProp minioProp;

    /**
     * 上传视频
     */
    @PostMapping("/insertVideo")
    @ApiOperation("上传视频")
    public Result insertVideo(@ApiParam("上传的文件") @RequestParam("file") MultipartFile file,
                              @ApiParam("科目号") @RequestParam("subjectId") String subjectId,
                              @ApiParam("章节号") @RequestParam("chapterId") String chapterId) {
        String filename = null;
        try {
            filename = file.getOriginalFilename();
            InputStream inputStream = file.getInputStream();
            //视频标题
            String videoTitle = filename.substring(0,filename.lastIndexOf("."));
            String pathName = UUID.randomUUID().toString().replaceAll("-","") + filename.substring(filename.lastIndexOf("."));
            //视频路径
            String videoPath = minioProp.getEndpoint() + "/" + MINIO_BUCKET + "/" + pathName;


            File f = File.createTempFile("tmp", filename.substring(filename.lastIndexOf(".") - 1));
            file.transferTo(f);
            f.deleteOnExit();
            //获取视频时长
            MultimediaObject instance = new MultimediaObject(f);
            MultimediaInfo result = instance.getInfo();
            double duration = result.getDuration();
            DecimalFormat df = new DecimalFormat("#.00");
            Double ls = Double.valueOf(df.format((duration / 1000) / 60));
            //minio上传视频文件
            PutObjectOptions putObjectOptions = new PutObjectOptions(file.getSize(), PutObjectOptions.MIN_MULTIPART_SIZE);
            putObjectOptions.setContentType(Objects.requireNonNull(file.getContentType()));

            minioClient.putObject(MINIO_BUCKET,pathName,inputStream,putObjectOptions);
            inputStream.close();
            VideoEntity videoEntity = new VideoEntity();
            videoEntity.setVideoTitle(videoTitle);
            videoEntity.setVideoPath(videoPath);
            videoEntity.setVideoLength(ls);
            videoEntity.setSubject(subjectId);
            videoEntity.setChapter(chapterId);
            videoEntity.setCompleteLength(Double.valueOf(df.format(0)));
            videoEntity.setId(UUID.randomUUID().toString().replaceAll("-",""));
            boolean update = videoEntityService.saveOrUpdate(videoEntity);
/*
            if (update) {
                SubjectEntity subjectEntity = subjectEntityService.getById(subjectId);
                subjectEntity.setAllLength(subjectEntity.getAllLength() + ls);
                boolean updateSubject = subjectEntityService.updateById(subjectEntity);
                if (updateSubject) {
                    return ResultFactory.success(videoEntity);
                }
            }
*/

            return ResultFactory.success(videoEntity);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultFactory.fail("上传视频失败！");
        }

    }

    /**
     * 将视频分配给学生
     */
    @PostMapping("/assignmentVideoToStu")
    @ApiOperation("将视频分配给学生")
    public Result assignmentVideoToStu(@ApiParam("学生分配视频Vo") @RequestBody VideoStuVo videoStuVo) {
        //获取视频id
        String videoId = videoStuVo.getVideoId();
        //获取分配学生id
        List<String> stuIdList = videoStuVo.getStuIdList();
        //通过视频id查询出视频信息
        VideoEntity videoEntity1 = videoEntityService.getById(videoId);
        //查询出全部科目表的信息
        Subject subjectServiceById = subjectService.getById(videoEntity1.getSubject());
        //获取科目类型
        Integer type = subjectServiceById.getType();
        for (String stuId : stuIdList) {
            //通过学生id查询出学生科目信息
            LambdaQueryWrapper<SubjectEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(SubjectEntity::getStuId,stuId).eq(SubjectEntity::getType,type);
            SubjectEntity subjectEntity = subjectEntityService.getOne(lambdaQueryWrapper);

            //新增视频对象
            VideoEntity videoEntity = new VideoEntity();
            videoEntity.setVideoTitle(videoEntity1.getVideoTitle());
            videoEntity.setVideoPath(videoEntity1.getVideoPath());
            videoEntity.setVideoLength(videoEntity1.getVideoLength());
            videoEntity.setSubject(subjectEntity.getStuId());
            videoEntity.setChapter(videoEntity1.getChapter());
            videoEntity.setCompleteLength(videoEntity1.getCompleteLength());
            videoEntity.setStuId(stuId);
            //videoEntity.setId("2");
            boolean save = videoEntityService.save(videoEntity);
            //修改科目对象
            if (save) {
                subjectEntity.setAllLength(subjectEntity.getAllLength() + videoEntity1.getVideoLength());
                boolean updateSubject = subjectEntityService.updateById(subjectEntity);
            }

        }
        //删除当前视频
        videoEntityService.removeById(videoEntity1.getId());
        return ResultFactory.success(true);

    }


    /**
     * 删除视频
     */
    @DeleteMapping("/insertVideo")
    public Result deleteVideo(@RequestBody List<String> ids) {
        boolean remove = videoEntityService.removeByIds(ids);
        if (remove) {
            return ResultFactory.success(true);
        }
        return ResultFactory.fail("删除视频失败！");
    }

    /**
     * 通过id查询视频
     */
    @PostMapping("/selectVideoById")
    public Result selectVideoById(@RequestParam("id") String id) {
        VideoEntity videoEntity = videoEntityService.getById(id);
        return ResultFactory.success(videoEntity);
    }

    /**
     * 通过课程id查询视频信息
     */
    @PostMapping("/selectVideoBySubjectId")
    @ApiOperation("通过课程id查询视频信息")
    public Result selectVideoBySubjectId(@RequestParam("subjectId") String subjectId,
                                         @ApiParam("学生id") @RequestParam("stuId") String stuId) {
        List<VideoEntity> videoEntityList = videoEntityService.selectVideoBySubjectId(subjectId,stuId);
        return ResultFactory.success(videoEntityList);
    }

    /**
     * 通过课程id与章节id查询视频信息
     */
    @PostMapping("/selectVideoBySubjectAndChapter")
    @ApiOperation("通过课程id与章节id查询视频信息")
    public Result selectVideoBySubjectAndChapter(@ApiParam("课程id") @RequestParam("subjectId") String subjectId,
                                                 @ApiParam("章节id") @RequestParam("chapterId") String chapterId,
                                                 @ApiParam("学生id") @RequestParam("stuId") String stuId) {
        List<Map<String,Object>> videoEntityList = videoEntityService.selectVideoBySubjectAndChapter(subjectId,chapterId,stuId);
        return ResultFactory.success(videoEntityList);
    }

    /**
     * 修改视频当前播放时间，并计算学习比例
     * @param id 视频id
     * @param currentTime 当前时间
     */
    @PostMapping("/updateVideoCompleteTime")
    @ApiOperation("修改视频当前播放时间，并计算学习比例")
    public Result updateVideoCompleteTime(@ApiParam("视频id") @RequestParam("id") String id,
                                          @ApiParam("当前时间") @RequestParam("currentTime") double currentTime) {
        boolean flag = videoEntityService.updateVideoCompleteTime(id,currentTime);
        if (flag) {
            return ResultFactory.success(true);
        }
        return ResultFactory.success("学习失败");
    }




}

